/*
 *  Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 *  This file is part of e3utils.
 *
 *  e3utils is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  e3utils is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with e3utils. If not, see <https://www.gnu.org/licenses/>.
 */

package safe

import (
	"errors"
	"fmt"
	"runtime"

	"gitee.com/ameise84/e3utils/internal"
)

type PanicHook interface {
	OnPanic(err error)
}

// Func 安全的执行f函数,如果panic会自动捕获
func Func(h PanicHook, where string, f func()) {
	doFunc(h, where, f)
}

// LoopFunc 循环执行函数,直到其正常退出.通常用于func函数需要循环执行,被异常中止后需要继续执行
func LoopFunc(h PanicHook, where string, f func()) {
	for {
		if doFunc(h, where, f) {
			break
		}
		runtime.Gosched()
	}
}

func doFunc(h PanicHook, where string, f func()) bool {
	defer RecoverPanic(h, where)
	f()
	return true
}

func RecoverPanic(h PanicHook, where string) {
	if x := recover(); x != nil {
		var msg string
		if where != "" {
			msg = fmt.Sprintf("[%s] %+v", where, x)
		} else {
			msg = fmt.Sprintf("%+v", x)
		}
		if h != nil {
			h.OnPanic(errors.New(msg))
		} else {
			internal.GetLogger().Error(msg).Println()
		}
	}
}
